package com.uking.util;

import android.content.SharedPreferences;
import android.os.Build.VERSION;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy.Builder;

import com.smalls.newvideotwo.utils.Constant;
import com.uking.helper.VKErrorMessageUtil;
import com.uking.helper.VKLogger;
import com.uking.moudle.IpInfo;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.regex.Pattern;

public class Utils {
    public static final String ENTRY_KEY = "aaa-addr";
    private static String TAG = Constant.baddcoolio2tag? Constant.TAGPREFIXSTR + "VKPortalProxy":"VKPortalProxy";
    public static String saveDateJson(ArrayList<IpInfo> list) {
        JSONObject json = new JSONObject();
        try {
            json.put(Constants.IP_PORT_LIST, list);
            return String.valueOf(json);
        } catch (JSONException e) {
            log("\u4fdd\u5b58\u5230json\u5931\u8d25");
            e.printStackTrace();
            return null;
        }
    }

    public static JSONObject getGrouping3AaddressFromNet(String strSn, String visitAddress) throws Exception {
        log("\u4ece\u7f51\u7edc\u4e2d\u83b7\u53d63A\u5730\u5740");
        JSONObject object = new JSONObject();
        object.put("sn", strSn);
        String encodeSn = DES.encryptDESURL(object.toString(), ENTRY_KEY);
        String address = visitAddress + Constants.GROUPING_SERVICE + encodeSn;
        if (!visitAddress.startsWith("http://")) {
            address = "http://" + visitAddress + Constants.GROUPING_SERVICE + encodeSn;
        }
        log("\u8bbf\u95ee\u7684address\u662f " + address);
        String result = DES.decryptDESURL(getFromNet(address), ENTRY_KEY);
        JSONObject jsonResult = new JSONObject(result);
        log("result=" + result);
        return jsonResult;
    }

    private static String getFromNet(String address) throws Exception {
        long startTime = System.currentTimeMillis();
        HttpURLConnection connection = (HttpURLConnection) new URL(address).openConnection();
        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);
        byte[] data = new byte[1024];
        InputStream inStream = connection.getInputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while (true) {
            int len = inStream.read(data);
            if (len == -1) {
                break;
            }
            outStream.write(data, 0, len);
        }
        inStream.close();
        outStream.close();
        long endTime = System.currentTimeMillis();
        String tmpAddress = StringUtil.subString(address);
        String ip = null;
        if (tmpAddress != null) {
            ip = domain2ip(tmpAddress);
        }
//        SepiaUtil.onBusEvent("3a", address, ip, (startTime / 1000) + "", endTime - startTime, connection.getResponseCode());
        return new String(outStream.toByteArray());
    }

    public static String domain2ip(String domain) {
        if (isIP(domain)) {
            log("\u662fip\u5730\u5740,\u76f4\u63a5\u8fd4\u56de\uff0c\u65e0\u9700\u89e3\u6790");
            return domain;
        }
        if (VERSION.SDK_INT > 9) {
            StrictMode.setThreadPolicy(new Builder().permitAll().build());
        }
        try {
            log("\u5f00\u59cb\u89e3\u6790" + domain);
            return InetAddress.getByName(domain).getHostAddress();
        } catch (UnknownHostException e) {
            log(" DNS\u89e3\u6790\u5931\u8d25");
            reportErrorMessage(domain);
            return null;
        }
    }

    public static void reportErrorMessage(String domain) {
        VKUmengCollection.collectionsDNSError(domain);
        VKErrorMessageUtil.setMessageInfo(VKConstant.AAA_PARSE_ERROR, "address parse failed");
    }

    public static void log(String s) {
        VKLogger.e(TAG, s);
    }

    public static void cacheDefault3AAddress(String mMainAddress, String mSecondAddress, int port, SharedPreferences sharedAAA) {
        ArrayList<IpInfo> list = new ArrayList();
        list.add(new IpInfo(mMainAddress, String.valueOf(port)));
        list.add(new IpInfo(mSecondAddress, String.valueOf(port)));
        sharedAAA.edit().putString(Constants.GROUPING_ADDRESS, replaceBlank(saveDateJson(list))).commit();
    }

    public static void set3AAddressCache(String cacheAddress, String aAAaddress, SharedPreferences sharedAAA) {
        ArrayList<IpInfo> list = new ArrayList();
        log("\u539f\u7f13\u5b58\u4e2d\u7684\u5730\u5740=" + cacheAddress);
        log("\u65b0\u7f13\u5b58\u7684\u5730\u5740=" + aAAaddress);
        list = getResolveAddress(aAAaddress);
        if (list.size() == 1) {
            log("\u65b0\u7f13\u5b58\u7684\u5730\u5740\u53ea\u6709\u4e00\u4e2a\uff0c\u5c06\u539f\u7f13\u5b58\u4e2d\u7684\u7b2c\u4e8c\u4e2a\u5730\u5740\u6dfb\u52a0\u8fdb\u65b0\u7684\u7f13\u5b58");
            ArrayList arrayList = new ArrayList();
            list.add((IpInfo) getResolveAddress(cacheAddress).get(1));
        }
        String address = replaceBlank(saveDateJson(list));
        log("\u65b0\u7684\u7f13\u5b58\u4e3a=" + address);
        sharedAAA.edit().putString(Constants.GROUPING_ADDRESS, address).commit();
    }

    public static ArrayList<IpInfo> getResolveAddress(String address) {
        ArrayList<IpInfo> list = new ArrayList();
        String[] info;
        IpInfo ipInfo;
        if (address.contains(",")) {
            for (String ipInfos : address.split(",")) {
                info = ipInfos.split(":");
                ipInfo = null;
                if (info.length > 1 && info[1] != null) {
                    ipInfo = new IpInfo(info[0], info[1]);
                } else if (info[0] != null) {
                    ipInfo = new IpInfo(info[0]);
                }
                if (ipInfo != null) {
                    list.add(ipInfo);
                }
            }
        } else {
            info = address.split(":");
            if (info != null && info.length > 0) {
                ipInfo = null;
                if (info.length > 1 && info[1] != null) {
                    ipInfo = new IpInfo(info[0], info[1]);
                } else if (info[0] != null) {
                    ipInfo = new IpInfo(info[0]);
                }
                if (ipInfo != null) {
                    list.add(ipInfo);
                }
            }
        }
        return list;
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            return Pattern.compile("\\s*|\t|\r|\n").matcher(str).replaceAll("");
        }
        return dest;
    }

    public static boolean isIP(String addr) {
        if (addr.length() < 7 || addr.length() > 15 || "".equals(addr)) {
            return false;
        }
        return Pattern.compile("([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}").matcher(addr).find();
    }
}
